package demo.booleanteeth.rxjavademo;

import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

public class TestActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "TestActivity";
    private int count = 0;
    private Button btTest;
    private boolean connect;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        btTest = ((Button) findViewById(R.id.bt_test));
        btTest.setOnClickListener(this);
        EventBus.getDefault().register(this);

        //定时2秒调用一次
        Flowable.interval(8, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(@NonNull Long aLong) throws Exception {
                        Log.e("zd", (aLong++) + "");
                        if (count % 3== 0) {
                            EventBus.getDefault().post(new EventBean("有卡", true));
                        } else {
                            EventBus.getDefault().post(new EventBean("无卡", false));
                        }
                        count++;
                    }
                });

    }

    // 订阅方法,当接受到事件后会调用
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventBean eventBean) {
        Log.i(TAG, "------------" + eventBean.getMessage());
        connect = eventBean.isConnect();
        Log.i(TAG, "-----"+connect);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_test:
                if (connect) {
                    Toast.makeText(this, "连接", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "断开", Toast.LENGTH_SHORT).show();
                }
                break;

        }
    }
}
